package model;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.table.AbstractTableModel;

import domain.Customer;
import domain.Library;

public class LoanMasterCustomerTableModel extends AbstractTableModel implements Observer {
    private static LoanMasterCustomerTableModel instance;
    private String[] columns = { "Vorname", "Nachname", "Strasse", "PLZ", "Ort" };
    private List<Customer> model;
    private final Library library;
    private static final long serialVersionUID = 2966279676059941187L;

    public static LoanMasterCustomerTableModel getInstance() {
        if (instance == null)
            instance = new LoanMasterCustomerTableModel();
        return instance;
    }

    private LoanMasterCustomerTableModel() {
        library = Library.getInstance();
        library.addObserver(this);
        model = new ArrayList<>(library.getCustomers());
        this.update(null, null);
    }

    @Override
    public void update(Observable obj, Object arg1) {
        List<Customer> modelOld = model;
        model = new ArrayList<>(library.getCustomers());
        for (int i = 0; i < model.size(); i++) {
            if (!modelOld.contains(model.get(i))) {
                this.fireTableRowsInserted(i, i);
            }
        }
        for (int i = 0; i < modelOld.size(); i++) {
            if (!model.contains(modelOld.get(i))) {
                this.fireTableRowsDeleted(i, i);
            }
        }
    }

    @Override
    public boolean isCellEditable(int arg0, int arg1) {
        return false;
    }

    @Override
    public String getColumnName(int column) {
        return columns[column];
    }

    @Override
    public int getColumnCount() {
        return columns.length;
    }

    @Override
    public int getRowCount() {
        return model.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Customer customer;
        customer = model.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return customer.getSurname();
            case 1:
                return customer.getName();
            case 2:
                return customer.getStreet();
            case 3:
                return customer.getZip();
            case 4:
                return customer.getCity();
            default:
                return null;
        }
    }

    public Customer getElementAt(int rowIndex) {
        return model.get(rowIndex);
    }

    @Override
    public Class<String> getColumnClass(int columnIndex) {
        return String.class;
    }

}
